package com.example.mymusic;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.RequiresApi;

/**
 * @author xky
 */
public class MyFlowerView extends View {

    private Bitmap bitmapBack = null;
    /**
     * view的宽和高
     */
    int mHeight = 0;
    int mWidth = 0;
    /**
     * 花形图片
     */
    public static Bitmap bitmap = null;
    /**
     * 用于限制大小
     */
    int radius = 0;
    /**
     * 旋转动画的矩形
     */
    Matrix matrix = new Matrix();
    /**
     * 旋转动画的角度
     */
    int degrees = 0;
    public static MyReceiver myReceiver=null;
    /**
     * 状态位,自动换成下一首时,先将旋转线程去掉
     */
    boolean flag=false;
    /**
     * -----------旋转动画-----------
     */
    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //旋转
            int halfRadius = radius / 2;
            matrix.postRotate(degrees++, halfRadius, halfRadius);
            //重绘
            invalidate();
            //延迟
            mHandler.postDelayed(runnable, 50);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void update(Context context){
        //根据播放状态，旋转暂停
        if (!MusicService.musicState){
            mHandler.removeCallbacks(runnable);
            flag = false;
        }else {
            if (flag){
                mHandler.removeCallbacks(runnable);
            }
            mHandler.post(runnable);
            flag=true;
        }


        if (MusicService.listMusic==null){
            MusicService.listMusic = Utils.getMusic(context);

        }
        if (MusicService.m_position ==MusicService.NOT_MUSIC){
            MusicService.m_position = 0;
        }

        //设置专辑图片
        bitmap = MusicService.bitmap;

        if (bitmap == null){
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yuantu2);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public MyFlowerView(Context context) {
        super(context);
        initView(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public MyFlowerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public MyFlowerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);

    }

    /**
     * 收到update_ui广播就更新
     */
    public class MyReceiver extends BroadcastReceiver {
        public MyReceiver() {
        }
        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onReceive(Context context, Intent intent) {
            update(context);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void initView(Context context) {

        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("update_ui");
        myReceiver = new MyReceiver();
        context.registerReceiver(myReceiver,intentFilter);

        //花朵图片
        bitmapBack = BitmapFactory.decodeResource(getResources(), R.drawable.flower1);

        update(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //测量整个View的宽和高
        mWidth = measuredWidth(widthMeasureSpec);
        mHeight = measuredHeight(heightMeasureSpec);
        setMeasuredDimension(mWidth, mHeight);
    }

    private int measuredWidth(int widthMeasureSpec) {
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        if (mode == MeasureSpec.EXACTLY) {
            mWidth = size;
        } else {
            //由图片决定宽度
            int value = getPaddingLeft() + getPaddingRight() + bitmapBack.getWidth();

            if (mode == MeasureSpec.AT_MOST) {
                //由图片和Padding决定宽度，但是不能超过View的宽
                mWidth = Math.min(value, size);
            }
        }
        return mWidth;
    }

    private int measuredHeight(int heightMeasureSpec) {

        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size;
        size = MeasureSpec.getSize(heightMeasureSpec);
        //EXACTLY，0 [0x0]，精确的，表示父view为子view确定精确的尺寸。fill_parent
        if (mode == MeasureSpec.EXACTLY) {
            mHeight = size;
        } else {
            //未加规定的，就由图片决定高度
            int value = getPaddingTop() + getPaddingBottom() + bitmapBack.getHeight();
            //AT_MOST，-2147483648 [0x80000000]，子view可以在指定的尺寸内尽量大。wrap_content
            if (mode == MeasureSpec.AT_MOST) {
                //由图片和Padding决定高度，但是不能超过View的高
                mHeight = Math.min(value, size);
            }
        }
        return mHeight;
    }

    /**
     * 设置大小
     */
    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.concat(matrix);
        //真实的半径必须是View的宽高最小值
        radius = Math.min(mWidth, mHeight);
        //如果图片本身宽高太大，进行相应的缩放
        bitmap = Bitmap.createScaledBitmap(bitmap, radius, radius, false);
        bitmapBack = Bitmap.createScaledBitmap(bitmapBack, radius, radius, false);
        //画花形图片
        canvas.drawBitmap(createFlowerImage(bitmap, radius), 0, 0, null);
        matrix.reset();
    }

    /**
     * 透明度，叠起来，绘制图片
     */
    private Bitmap createFlowerImage(Bitmap source, int radius) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
        //产生一个同样大小的画布
        Canvas canvas = new Canvas(target);
        //首先绘制图形
        canvas.drawBitmap(bitmapBack,0,0,paint);
        //使用SRC_IN模式显示后画图的交集处
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //绘制图片，从（0，0）画
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }
}
